package com.cat.dataStructure;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/find-kth-largest-xor-coordinate-value/description/
 * @create 2025/8/20 16:24
 * @since JDK17
 */

public class Solution42 {
    int n, m;
    int[][] arr;

    int sum(int a, int b, int c, int d) {
        return arr[c + 1][d + 1] ^ arr[c + 1][b] ^ arr[a][d + 1] ^ arr[a][b];
    }

    public int kthLargestValue(int[][] mat, int k) {
        n = mat.length;
        m = mat[0].length;
        arr = new int[n + 1][m + 1];
        List<Integer> list = new ArrayList<>();
        for (int a = 1, b = 0; b < n; a++, b++) {
            for (int c = 1, d = 0; d < m; c++, d++) {
                arr[a][c] = mat[b][d];
            }
        }
        for (int i = 1; i <= n; i++) {  // 制作前缀和数组
            for (int j = 1; j <= m; j++) {
                arr[i][j] ^= arr[i - 1][j] ^ arr[i][j - 1] ^ arr[i - 1][j - 1];
            }
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                list.add(sum(0, 0, i, j));
            }
        }
        Collections.sort(list);
        return list.get(list.size() - k);
    }
}
